﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DevelopAssistant.Format
{
    /// <summary>
    /// 功能描述：Json 格式化 
    /// 版本号：v 1.0.0
    /// 创建作者：王晓东
    /// 更新时间：2016-02-17
    /// </summary>
    public class JsonFormatHelper
    {
        /// <summary>
        /// 格式化为Json 字符串
        /// </summary>
        /// <param name="strjson">Json 字符串</param>
        /// <param name="arrepl">需要替换的字符串</param>
        /// <returns></returns>
        public static string FormatToJson(string strjson, Dictionary<string, string> arrepl = null)
        {
            string result = string.Empty;
            try
            {
                if (string.IsNullOrEmpty(strjson))
                    return strjson;

                int temp_index = 0;//临时记数              

                strjson = strjson.Replace('\r', ' ').Replace('\n', ' ');

                char[] chr_array = strjson.ToCharArray();
                List<char> chr_list = new List<char>();

                #region 处理换行，去除空格

                for (int i = 0, len = chr_array.Length; i < len; i++)
                {
                    char chr = chr_array[i];

                    if (chr != ' ')
                    {
                        if (chr != '{' && chr != '}' && chr != ',' && chr != '[' && chr != ']')
                        {
                            chr_list.Add(chr);
                        }
                        else
                        {
                            if (chr == '{' || chr == '[')
                            {
                                chr_list.Add(chr);
                                chr_list.Add('\n');
                            }
                            if (chr == '}' || chr == ']')
                            {
                                chr_list.Add('\n');
                                chr_list.Add(chr);
                            }
                            if (chr == ',')
                            {
                                chr_list.Add(chr);
                                chr_list.Add('\n');
                            }
                        }
                    }

                }

                #endregion

                string temp_str = string.Concat(chr_list.ToArray());

                //替换字符
                if (arrepl != null)
                {
                    foreach (var key in arrepl.Keys)
                    {
                        temp_str = temp_str.Replace(key, arrepl[key]);
                    }
                }

                #region 处理缩进,格式化样式

                string tab = "   ";
                string[] str_lines = temp_str.Split('\n');
                foreach (string line in str_lines)
                {
                    string temp_line = line.ToString();               

                    if (line == "{" || line == "[")
                    {
                        temp_index = temp_index + 1;
                        for (int j = 1; j < temp_index; j++)
                        {
                            temp_line = tab + temp_line;
                        }
                    }

                    if (line == "}" || line == "]")
                    {
                        for (int j = 1; j < temp_index; j++)
                        {
                            temp_line = tab + temp_line;
                        }
                        temp_index = temp_index - 1;
                    }

                    if (line.Contains("},"))
                    {
                        for (int j = 1; j < temp_index; j++)
                        {
                            temp_line = tab + temp_line;
                        }
                        temp_index = temp_index - 1;
                    }

                    if (line.Contains("],"))
                    {
                        for (int j = 1; j < temp_index; j++)
                        {
                            temp_line = tab + temp_line;
                        }
                        temp_index = temp_index - 1;
                    }

                    if (line.Contains(":[") || line.Contains(":{"))
                    {
                        for (int j = 0; j < temp_index; j++)
                        {
                            temp_line = tab + temp_line;
                        }
                        temp_index = temp_index + 1;
                    }

                    if (line.ToLower().Contains("){"))
                    {
                        temp_index = temp_index + 1;
                    }


                    if (line != "[" && line != "{" && line != "}" && line != "]" && line != "},"
                        && line != "]," && !line.Contains(":[") && !line.Contains(":{"))
                    {
                        for (int j = 0; j < temp_index; j++)
                        {
                            temp_line = tab + temp_line;
                        }
                    }                    

                    result = result + temp_line + "\r\n";

                }

                #endregion

                temp_str = null;
                chr_list.Clear();
                chr_list = null;

            }
            catch (Exception ex)
            {
                result = strjson;
            }
            return result;

        }

        /// <summary>
        /// Json 字符串压缩
        /// </summary>
        /// <param name="strjson">Json 字符串</param>
        /// <param name="arrepl">需要替换的字符串</param>
        /// <returns></returns>
        public static string CompressToString(string strjson, Dictionary<string, string> arrepl = null)
        {
            string result = string.Empty;

            //替换字符
            if (arrepl != null)
            {
                foreach (var key in arrepl.Keys)
                {
                    strjson = strjson.Replace(key, arrepl[key]);
                }
            }

            strjson = strjson.Replace('\r', ' ').Replace('\n', ' ');
            strjson = strjson.Replace('\t', ' ').Replace(" ","");

            result = strjson;

            return result;
        }
    }
}
